package pzc.security;

import java.security.Provider;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

public class MyDESTest {
	public static String doEncrypt(String key, String plainText) throws Exception {
		Provider sunJce = new com.sun.crypto.provider.SunJCE();
		Security.addProvider(sunJce);

		Cipher c = Cipher.getInstance("DES");
		SecretKeyFactory keyFac = SecretKeyFactory.getInstance("DES");
		DESKeySpec keySpec = new DESKeySpec(key.getBytes());
		SecretKey secKey = keyFac.generateSecret(keySpec);

		c.init(Cipher.ENCRYPT_MODE, secKey);
		byte[] b = c.doFinal(plainText.getBytes());
		return new sun.misc.BASE64Encoder().encode(b);
	}

	public static String doDecrypt(String key, String cipherText) throws Exception {

		Provider sunJce = new com.sun.crypto.provider.SunJCE();
		Security.addProvider(sunJce);

		Cipher c = Cipher.getInstance("DES");
		SecretKeyFactory keyFac = SecretKeyFactory.getInstance("DES");
		DESKeySpec keySpec = new DESKeySpec(key.getBytes());
		SecretKey secKey = keyFac.generateSecret(keySpec);

		byte[] b = new sun.misc.BASE64Decoder().decodeBuffer(cipherText);
		c.init(Cipher.DECRYPT_MODE, secKey);
		return new String(c.doFinal(b));
	}

	public static void main(String[] args) {

		String key = "abcd1234";
		String source = "1234567812345678";
		String destination = null;

		try {
			System.out.println("source: " + source);

			destination = doEncrypt(key, source);
			System.out.println("destination: " + destination);

			String decrypted = doDecrypt(key, destination);
			System.out.println("decrypted: " + decrypted);
		} catch (Exception e) {
		}

	}
}
